﻿// 麻省理工学院许可证
//
// 版权所有 (c) 2023-2025 缄默 联系电话/18521355630 
//
// 特此免费授予获得本软件的任何人以处理本软件的权利，但须遵守以下条件：在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
//
// 软件按“原样”提供，不提供任何形式的明示或暗示的保证，包括但不限于对适销性、适用性和非侵权的保证。
// 在任何情况下，作者或版权持有人均不对任何索赔、损害或其他责任负责，无论是因合同、侵权或其他方式引起的，与软件或其使用或其他交易有关。

using Infragistics.Win;
using Infragistics.Win.FormattedLinkLabel;
using Infragistics.Win.UltraWinGrid;

namespace LvcChong
{
    public static class UltraGridExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="band"></param>
        /// <param name="key"></param>
        /// <param name="caption"></param>
        /// <param name="originX"></param>
        /// <param name="columns"></param>
        /// 
        /// <remarks>
        /// 使用示例：
        /// <code>
        /// 先设置分组呈现方式
        /// band.RowLayoutStyle = Infragistics.Win.UltraWinGrid.RowLayoutStyle.GroupLayout;
        /// 
        /// 再设置不用分组的列的位置和高度
        /// band.Columns["AreaName"].RowLayoutColumnInfo.SpanY = 4;
        /// band.Columns["AreaName"].RowLayoutColumnInfo.OriginX = 0;
        /// band.Columns["SnapshotTime"].RowLayoutColumnInfo.SpanY = 4;
        /// band.Columns["SnapshotTime"].RowLayoutColumnInfo.OriginX = 2;
        /// 
        /// 最后设置分组有哪些列，每一列占2个单位的origin
        /// band.AddGroup("gongzhu", "公猪段", 4, band.Columns["BoarsSemenCount"], band.Columns["BoarsSeductionCount"]);
        /// band.AddGroup("huaiyun", "怀孕段", 8, band.Columns["SowsReserveCount"], band.Columns["SowsBarrenCount"]);
        /// </code>
        /// </remarks>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public static UltraGridGroup AddGroup(this UltraGridBand band, string key, string caption, int originX, params UltraGridColumn[] columns)
        {
            if (columns == null || columns.Length == 0) throw new InvalidOperationException("必须有加入分组的列参数");

            var group = band.Groups.Add(key, caption);
            group.RowLayoutGroupInfo.OriginX = originX;
            group.RowLayoutGroupInfo.SpanX = columns.Select(x => x.RowLayoutColumnInfo.SpanX).Sum();
            group.RowLayoutGroupInfo.SpanY = columns.First().RowLayoutColumnInfo.SpanY;
            group.RowLayoutGroupInfo.PreferredLabelSize = columns.First().RowLayoutColumnInfo.PreferredLabelSize;

            foreach (var item in columns.OrderBy(x => x.RowLayoutColumnInfo.OriginX))
            {
                item.RowLayoutColumnInfo.ParentGroup = group;
            }
            return group;
        }

        public static UltraGridColumn AddLinkedColumn(this UltraGridBand band,
            string caption,
            Infragistics.Win.FormattedLinkLabel.LinkClickedEventHandler clickAction,
            List<UltraGridDisplayItem> defaultValue = null!,
            Action<UltraGridColumn> linkedColumn = null!)
        {
            if (!band.Columns.Exists(caption))
            {
                UltraGridColumn col = band.Columns.Add(caption);
                var linkLable = new UltraFormattedLinkLabel
                {
                    UnderlineLinks = UnderlineLink.Never
                };
                // 设置点击前后样式一样
                linkLable.LinkAppearance.ForeColor = Color.Blue;
                linkLable.VisitedLinkAppearance.ForeColor = Color.Blue;
                linkLable.HotTrackLinkAppearance.ForeColor = Color.Blue;
                linkLable.LinkClicked += (s, e) =>
                {
                    // 不打开超链接
                    e.OpenLink = false;
                    clickAction?.Invoke(s, e);
                };
                col.Header.Caption = caption;
                col.Key = caption;
                col.EditorComponent = linkLable;
                col.CellClickAction = CellClickAction.RowSelect;
                col.CellActivation = Activation.ActivateOnly;
                col.AutoEditMode = DefaultableBoolean.False;
                col.Width = 200;
                col.AllowRowFiltering = DefaultableBoolean.False;
                col.AllowGroupBy = DefaultableBoolean.False;
                col.AllowRowSummaries = AllowRowSummaries.False;
                col.Header.Appearance.TextHAlign = HAlign.Center;
                col.Header.Appearance.TextVAlign = VAlign.Middle;
                col.CellAppearance.TextHAlign = HAlign.Center;
                col.CellAppearance.TextVAlign = VAlign.Middle;
                col.Header.Fixed = true;
                col.Header.VisiblePosition = 9999;
                col.Header.FixOnRight = DefaultableBoolean.True;
                linkedColumn?.Invoke(col);
                List<string> content = new List<string>();
                if (defaultValue != null!)
                    foreach (var item in defaultValue)
                    {
                        content.Add(@$"<a style='display:block;fore-color:#379bce;text-align:center' href='{item.Key}'>{item.Caption}</a>");
                    }
                col.DefaultCellValue = string.Join(" ", content.ToArray());
                return col;
            }

            return band.Columns[caption];
        }

        public static UltraGridColumn AddUnBoundColumn(this UltraGrid grid,
               string key,
               string caption,
               Infragistics.Win.UltraWinGrid.ColumnStyle type,
               string defaultValue = "",
               AppearanceBase cellAppearance = null!,
               AppearanceBase headerAppearance = null
               )
        {
            if (grid.DisplayLayout.Bands[0].Columns.Cast<UltraGridColumn>().Count(c => c.Key == key) > 0)
                return grid.DisplayLayout.Bands[0].Columns[key];
            var col = grid.DisplayLayout.Bands[0].Columns.Add(key, caption);
            col.Style = type;
            //col.NullText = defaultValue;
            col.CellClickAction = CellClickAction.RowSelect;
            if (cellAppearance != null!) col.CellAppearance = cellAppearance;
            else
            {
                col.CellAppearance.TextHAlign = HAlign.Center;
                col.CellAppearance.TextVAlign = VAlign.Middle;
            }
            if (headerAppearance != null!) col.Header.Appearance = cellAppearance;
            else
            {
                col.Header.Appearance.TextHAlign = HAlign.Center;
                col.Header.Appearance.TextVAlign = VAlign.Middle;
            }

            // 针对NullText属性不生效的处理情况
            if (!string.IsNullOrEmpty(caption))
            {
                foreach (var item in grid.Rows)
                    item.Cells[key].Value = defaultValue;
            }
            return col;
        }

        public static void SetCellValueList(this UltraGridCell cell, IValueList valueList)
        {
            cell.ValueList = valueList;
            cell.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
        }

        public static void SetColumnValueList(this UltraGridColumn column, IValueList valueList)
        {
            column.ValueList = valueList;
            column.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
            column.CellActivation = Activation.ActivateOnly;
        }

        public static void SetLinkedValue(this UltraGridColumn column, Action<object, Infragistics.Win.FormattedLinkLabel.LinkClickedEventArgs> linkClickHandler)
        {
            var linkLable = new UltraFormattedLinkLabel
            {
                UnderlineLinks = UnderlineLink.Never
            };
            // 设置点击前后样式一样
            linkLable.LinkAppearance.ForeColor = Color.Blue;
            linkLable.VisitedLinkAppearance.ForeColor = Color.Blue;
            linkLable.HotTrackLinkAppearance.ForeColor = Color.Blue;
            linkLable.LinkClicked += (s, e) =>
            {
                // 不打开超链接
                e.OpenLink = false;
                linkClickHandler(s, e);
            };
            column.EditorComponent = linkLable;
        }

        public static void AddSummary(this UltraGridBand band, SummaryType summaryType, UltraGridColumn summaryColumn, SummaryPosition summaryPosition,
            string displayFormat = "总数 = {0}", bool useDefaultSummaryStyle = false)
        {
            if (useDefaultSummaryStyle) band.SetDefaultBrandSummaryStyle();
            if (band.Columns.Count > 0)
            {
                var s1 = band.Summaries.Add(summaryType, summaryColumn, summaryPosition);
                s1.DisplayFormat = displayFormat;
                s1.Appearance.FontData.Bold = DefaultableBoolean.True;
                s1.Appearance.FontData.Name = "微软雅黑";
                s1.Appearance.FontData.SizeInPoints = 10;
                s1.Appearance.ForeColor = Color.SteelBlue;
                s1.Appearance.TextVAlign = VAlign.Middle;
                s1.Appearance.TextHAlign = HAlign.Center;
                s1.Lines = 1;
            }
        }

        public static void AddSummary(this UltraGridBand band, ICustomSummaryCalculator customSummaryCalculator, UltraGridColumn summaryColumn, SummaryPosition summaryPosition,
            string displayFormat = "总数 = {0}", bool useDefaultSummaryStyle = false)
        {
            if (useDefaultSummaryStyle) band.SetDefaultBrandSummaryStyle();
            if (band.Columns.Count > 0)
            {
                var s1 = band.Summaries.Add(SummaryType.Custom, customSummaryCalculator, summaryColumn, summaryPosition, summaryColumn);
                s1.DisplayFormat = displayFormat;
                s1.Appearance.FontData.Bold = DefaultableBoolean.True;
                s1.Appearance.FontData.Name = "微软雅黑";
                s1.Appearance.FontData.SizeInPoints = 10;
                s1.Appearance.ForeColor = Color.SteelBlue;
                s1.Appearance.TextVAlign = VAlign.Middle;
                s1.Appearance.TextHAlign = HAlign.Center;
                s1.Lines = 1;
            }
        }

        public static void SetDefaultBrandSummaryStyle(this UltraGridBand band)
        {
            band.Override.SummaryDisplayArea = SummaryDisplayAreas.BottomFixed;
            band.Override.SummaryValueAppearance.BackColor = Color.White;
            band.Override.BorderStyleSummaryValue = UIElementBorderStyle.None;
            band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            band.Override.SummaryValueAppearance.BorderColor = Color.Transparent;
            band.Override.SummaryFooterAppearance.BorderColor = Color.Transparent;
        }

        public static void ApplyBackground(this UltraGridLayout ultraGridLayout, System.Drawing.Image image, ImageBackgroundStyle imageBackgroundStyle = Infragistics.Win.ImageBackgroundStyle.Tiled)
        {
            ultraGridLayout.Appearance.ImageBackground = image;
            ultraGridLayout.Appearance.ImageBackgroundStyle = imageBackgroundStyle;

            ultraGridLayout.Override.RowAppearance.BackColorAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.RowAppearance.ImageBackgroundAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.RowAppearance.BorderAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.RowAppearance.ImageAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.RowAppearance.ForegroundAlpha = Infragistics.Win.Alpha.UseAlphaLevel;

            // Explicitly set these to maximize performance and minimize context switches
            //
            ultraGridLayout.Override.CellAppearance.BackColorAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.CellAppearance.ImageBackgroundAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.CellAppearance.BorderAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.CellAppearance.ImageAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.CellAppearance.ForegroundAlpha = Infragistics.Win.Alpha.UseAlphaLevel;

            // Explicitly set these to maximize performance and minimize context switches
            //
            ultraGridLayout.Override.HeaderAppearance.BackColorAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.HeaderAppearance.ImageBackgroundAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.HeaderAppearance.BorderAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.HeaderAppearance.ImageAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
            ultraGridLayout.Override.HeaderAppearance.ForegroundAlpha = Infragistics.Win.Alpha.UseAlphaLevel;
        }

        public static void AddContextMenu(this UltraGrid grid, string text, EventHandler? menuItemClickHandler = null)
        {
            var menuTrip = grid.ContextMenuStrip;
            var mnuImport = menuTrip.Items.Add(text);
            if (menuItemClickHandler != null) mnuImport.Click += menuItemClickHandler;
        }
    }
}